package com.example.blog.controller;

import com.example.blog.base.Result;
import com.example.blog.util.MinioStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件模块
 * @ClassName FileController
 * @Description TODO
 * @Author Wang Li Hong
 * @date 2024/1/10 14:42
 * @Version 1.0
 */

@RestController
@RequestMapping("/file")
public class FileController {


    @Autowired
    private MinioStorage minioStorage;

    @Value("${minio.bucket-name}")
    private String bucketName;

    /**
     * 单个上传文件
     * @param multipartFile 文件
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile multipartFile) {
        String name = minioStorage.upload(multipartFile,bucketName);
        return Result.successData(name);
    }

    /**
     * 批量文件上传
     * @param multipartFiles
     * @return
     */
    @PostMapping("/uploads")
    public Result<String[]> upload(MultipartFile[] multipartFiles) {
        String[] names = minioStorage.upload(multipartFiles, bucketName);
        return Result.successData(names);
    }


    /**
     * 文件下载
     * @param fileName 文件名称
     * @return
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> download(@RequestParam String fileName) {
        byte[] bytes = minioStorage.download(fileName, bucketName);
        ByteArrayResource resource = new ByteArrayResource(bytes);
        // 设置ContentType
        MediaType mediaType = MediaTypeFactory.getMediaType(fileName)
                .orElse(MediaType.APPLICATION_OCTET_STREAM);

        return ResponseEntity.ok()
                // 指定文件名
                .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(fileName).build().toString())
                // 指定返回格式，png、zip、iso等等
                .contentType(mediaType)
                // 返回体
                .body(resource);
    }

    /**
     * 删除文件
     * @param filename 文件名称
     * @return
     */
    @DeleteMapping("/delete")
    public Result<Void> delete(String filename) {
        minioStorage.delete(filename, bucketName);
        return Result.success();
    }
}
